/*
 * @Author: 小程序面包园 1204593359@qq.com
 * @Date: 2024-05-20 13:57:13
 * @LastEditors: 小程序面包园 1204593359@qq.com
 * @LastEditTime: 2024-05-20 15:09:12
 * @FilePath: /vscode/UDP_Remote_Command/UDP_client.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once
#include <iostream>
#include <cerrno>
#include <unistd.h>
#include <string>
#include <strings.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"
#include "Comm.hpp"
#include "sockaddr.hpp"
#define BUFFERSIZE 1024

class UDP_client
{
public:
    UDP_client(std::string &server_ip, in_port_t server_port)
        : _sockfd(-1), _sk({server_ip, server_port})
    {
    }
    ~UDP_client()
    {
        close(_sockfd);
    }

    void Init()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd == -1)
        {
            _log.LogMessage(ClassFile, Error, "client socket error -> errno : %d strerror : %s\n", errno, strerror(errno));
            exit(SocketError);
        }
        _log.LogMessage(ClassFile, Info, "client socket success, _fd = %d\n", _sockfd);
    }

    void Send()
    {
        while (true)
        {
            std::string buffer;
            std::cout << "Please cin : ";
            std::getline(std::cin, buffer);

            ssize_t ret = sendto(_sockfd, buffer.c_str(), buffer.size(), 0, (struct sockaddr *)(&_sk.addr_in()), _sk.len());

            //发送信息成功
            if (ret > 0)
            {

                //接收返回结果
                char result[1024];
                ssize_t ret2 = recvfrom(_sockfd, result, sizeof(result), 0, (sockaddr *)(&_sk.addr_in()), &_sk.len());
                if(ret2 > 0)
                {
                    result[ret2] = 0;
                    std::cout <<  result << std::endl;
                }
                else
                {
                    _log.LogMessage(ClassFile, Error, "client recvfrom error -> errno : %d strerror : %s\n", errno, strerror(errno));
                    break;
                }
            }
            else
            {
                _log.LogMessage(ClassFile, Error, "client sendto error -> errno : %d strerror : %s\n", errno, strerror(errno));
                break;
            }
        }
    }

private:
    int _sockfd;
    Sockaddr _sk; // 填充server信息，以便在sendto中传递
};